<template>
  <el-card class="advanced-settings-card" shadow="never">
    <template #header>
      <div class="card-header">
        <span>团队设置</span>
        <el-button
          :icon="Refresh"
          size="small"
          @click="() => refreshSettings(true)"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </template>

    <div class="settings-content">
      <!-- 团队可见性设置 -->
      <div class="setting-section">
        <h4 class="section-title">
          <el-icon><View /></el-icon>
          团队可见性
        </h4>
        <div class="setting-item">
          <div class="setting-info">
            <div class="setting-name">团队可见性</div>
            <div class="setting-description">控制团队在系统中的可见性</div>
          </div>
          <div class="setting-control">
            <el-radio-group 
              v-model="settings.visibility" 
              @change="handleVisibilityChange"
              :disabled="!canManageSettings"
            >
              <el-radio value="PUBLIC">
                <div class="radio-content">
                  <el-icon><Connection /></el-icon>
                  <div>
                    <div class="radio-title">公开</div>
                    <div class="radio-desc">所有用户都可以看到团队</div>
                  </div>
                </div>
              </el-radio>
              <el-radio value="INTERNAL">
                <div class="radio-content">
                  <el-icon><OfficeBuilding /></el-icon>
                  <div>
                    <div class="radio-title">内部</div>
                    <div class="radio-desc">只有组织内用户可以看到</div>
                  </div>
                </div>
              </el-radio>
              <el-radio value="PRIVATE">
                <div class="radio-content">
                  <el-icon><Lock /></el-icon>
                  <div>
                    <div class="radio-title">私有</div>
                    <div class="radio-desc">只有团队成员可以看到</div>
                  </div>
                </div>
              </el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>

      <!-- 加入方式设置 -->
      <div class="setting-section">
        <h4 class="section-title">
          <el-icon><UserFilled /></el-icon>
          加入方式
        </h4>
        <div class="setting-item">
          <div class="setting-info">
            <div class="setting-name">成员加入方式</div>
            <div class="setting-description">控制新成员如何加入团队</div>
          </div>
          <div class="setting-control">
            <el-radio-group 
              v-model="settings.joinMethod" 
              @change="handleJoinMethodChange"
              :disabled="!canManageSettings"
            >
              <el-radio value="INVITE_ONLY">
                <div class="radio-content">
                  <el-icon><Message /></el-icon>
                  <div>
                    <div class="radio-title">仅邀请</div>
                    <div class="radio-desc">只能通过邀请加入</div>
                  </div>
                </div>
              </el-radio>
              <el-radio value="REQUEST">
                <div class="radio-content">
                  <el-icon><ChatDotRound /></el-icon>
                  <div>
                    <div class="radio-title">申请加入</div>
                    <div class="radio-desc">用户可以申请加入，需要审核</div>
                  </div>
                </div>
              </el-radio>
              <el-radio value="OPEN">
                <div class="radio-content">
                  <el-icon><Unlock /></el-icon>
                  <div>
                    <div class="radio-title">开放加入</div>
                    <div class="radio-desc">用户可以直接加入</div>
                  </div>
                </div>
              </el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>



      <!-- 安全设置 -->
      <div class="setting-section">
        <h4 class="section-title">
          <el-icon><Warning /></el-icon>
          安全设置
        </h4>
        <div class="setting-item">
          <div class="setting-info">
            <div class="setting-name">两步验证</div>
            <div class="setting-description">要求团队成员启用两步验证</div>
          </div>
          <div class="setting-control">
            <el-switch 
              v-model="settings.requireTwoFactor"
              @change="handleTwoFactorChange"
              :disabled="!canManageSettings"
              active-text="必须"
              inactive-text="可选"
            />
          </div>
        </div>
        <div class="setting-item">
          <div class="setting-info">
            <div class="setting-name">会话超时</div>
            <div class="setting-description">团队成员的会话超时时间（小时）</div>
          </div>
          <div class="setting-control">
            <el-input-number
              v-model="settings.sessionTimeout"
              @change="handleSessionTimeoutChange"
              :disabled="!canManageSettings"
              :min="1"
              :max="168"
              :step="1"
              controls-position="right"
            />
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="setting-actions" v-if="canManageSettings">
        <el-button 
          type="primary" 
          @click="saveSettings"
          :loading="saving"
        >
          保存设置
        </el-button>
        <el-button @click="resetSettings">
          重置
        </el-button>
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh,
  View,
  Connection,
  OfficeBuilding,
  Lock,
  UserFilled,
  Message,
  ChatDotRound,
  Unlock,
  Key,
  Warning
} from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import { teamApi } from '@/api/team'
import type {
  TeamSettings,
  TeamSettingsRequest
} from '@/types/team'

interface Props {
  teamId: number
  currentUserRole: string
}

const props = defineProps<Props>()
const { t } = useI18n()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const settings = ref<TeamSettings>({
  teamId: props.teamId,
  visibility: 'INTERNAL',
  joinMethod: 'INVITE_ONLY',
  defaultPermissions: ['VIEW_MEMBERS'],
  enableNotifications: true,
  notificationTypes: ['MEMBER_JOIN', 'MEMBER_LEAVE'],
  requireTwoFactor: false,
  sessionTimeout: 24,
  allowMemberInvite: false,
  allowMemberCreateProject: false,
  allowMemberManageFiles: false
})

const originalSettings = ref<TeamSettings>({ ...settings.value })

// 计算属性
const canManageSettings = computed(() => {
  return props.currentUserRole === 'OWNER' || props.currentUserRole === 'ADMIN'
})

// 方法
const refreshSettings = async (showSuccessMessage = false) => {
  loading.value = true
  try {
    const response = await teamApi.getTeamSettings(props.teamId)
    // RickPan API返回格式：{code: 200, message: '获取成功', data: {...}}
    if (response.code === 200 && response.data) {
      settings.value = response.data
      originalSettings.value = { ...response.data }
      // 只有手动刷新时才显示成功消息
      if (showSuccessMessage) {
        ElMessage.success('设置已刷新')
      }
    } else {
      ElMessage.error(response.message || '获取团队设置失败')
    }
  } catch (error: any) {
    console.error('刷新设置失败:', error)
    ElMessage.error(error.response?.data?.message || '刷新设置失败')
  } finally {
    loading.value = false
  }
}

const saveSettings = async () => {
  saving.value = true
  try {
    const request: TeamSettingsRequest = {
      visibility: settings.value.visibility,
      joinMethod: settings.value.joinMethod,
      requireTwoFactor: settings.value.requireTwoFactor,
      sessionTimeout: settings.value.sessionTimeout,
      // 保留这些字段以保持API兼容性，但设置为默认值
      defaultPermissions: ['VIEW_MEMBERS'],
      enableNotifications: true,
      notificationTypes: ['MEMBER_JOIN', 'MEMBER_LEAVE'],
      allowMemberInvite: false,
      allowMemberCreateProject: false,
      allowMemberManageFiles: false
    }

    const response = await teamApi.updateTeamSettings(props.teamId, request)
    // RickPan API返回格式：{code: 200, message: '获取成功', data: {...}}
    if (response.code === 200 && response.data) {
      settings.value = response.data
      originalSettings.value = { ...response.data }
      ElMessage.success('设置已保存')
    } else {
      ElMessage.error(response.message || '保存团队设置失败')
    }
  } catch (error: any) {
    console.error('保存设置失败:', error)
    ElMessage.error(error.response?.data?.message || '保存设置失败')
  } finally {
    saving.value = false
  }
}

const resetSettings = () => {
  settings.value = { ...originalSettings.value }
  ElMessage.info('设置已重置')
}

// 设置变更处理
const handleVisibilityChange = (value: string) => {
  console.log('可见性变更:', value)
}

const handleJoinMethodChange = (value: string) => {
  console.log('加入方式变更:', value)
}

const handleTwoFactorChange = (value: boolean) => {
  console.log('两步验证变更:', value)
}

const handleSessionTimeoutChange = (value: number) => {
  console.log('会话超时变更:', value)
}

// 生命周期
onMounted(() => {
  refreshSettings()
})
</script>

<style scoped lang="scss">
.advanced-settings-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .settings-content {
    .setting-section {
      margin-bottom: 32px;
      padding-bottom: 24px;
      border-bottom: 1px solid var(--el-border-color-lighter);

      &:last-child {
        border-bottom: none;
        margin-bottom: 0;
      }

      .section-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
        margin: 0 0 16px 0;
      }

      .setting-item {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16px;

        &:last-child {
          margin-bottom: 0;
        }

        .setting-info {
          flex: 1;
          margin-right: 24px;

          .setting-name {
            font-size: 14px;
            font-weight: 500;
            color: var(--el-text-color-primary);
            margin-bottom: 4px;
          }

          .setting-description {
            font-size: 12px;
            color: var(--el-text-color-secondary);
            line-height: 1.4;
          }
        }

        .setting-control {
          flex-shrink: 0;
          min-width: 200px;

          .radio-content {
            display: flex;
            align-items: center;
            gap: 8px;

            .radio-title {
              font-size: 14px;
              font-weight: 500;
              color: var(--el-text-color-primary);
            }

            .radio-desc {
              font-size: 12px;
              color: var(--el-text-color-secondary);
            }
          }
        }
      }
    }

    .setting-actions {
      display: flex;
      gap: 12px;
      padding-top: 24px;
      border-top: 1px solid var(--el-border-color-lighter);
    }
  }
}

:deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  gap: 12px;

  .el-radio {
    margin-right: 0;
    margin-bottom: 0;
  }
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;

  .el-checkbox {
    margin-right: 0;
  }
}
</style>
